iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0

終於快結束了!
今天的題目大意是:在一個已經由小到大排序的整數陣列 nums 中,用二分法找出目標值 target 的索引;找不到就回傳 -1

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1;
    }
}

上一篇
LeetCode 206. Reverse Linked List
下一篇
週三之LeetCode 83. Remove Duplicates from Sorted List
系列文
Chatting with ChatGPT——一天學習一題Leetcode23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言